<?php
	
if($_SERVER['REQUEST_METHOD'] == 'GET')
{
	//sleep(0.5);
	echo 'Get was used.<br/>';
	if($_GET['event'] == null)
	{
		echo 'No event was received.<br/>';
		echo '<script>self.location="event.php?event=renderClasses"</script>';
	}
	else
	{
		$eventType = $_GET['event'];
		echo "Need to process the event: '$eventType' <br/>";
		if($eventType == "renderClasses")
		{
			renderClasses();
		}
		elseif($eventType == "renderStudyGroups")
		{
			renderStudyGroups();
		}
		elseif($eventType == "renderStudyGroupPosts")
		{
			renderStudyGroupPosts();
		}
		elseif($eventType == "createNewStudyGroup")
		{
			createNewStudyGroup();
		}
		elseif($eventType == "deleteStudyGroup")
		{
			deleteStudyGroup();
		}
		elseif($eventType == "renderSearchPage")
		{
			renderSearchPage();
		}
		elseif($eventType == "displaySearchResults")
		{
			displaySearchResults();
		}
		elseif($eventType == "renderProfilePage")
		{
			renderProfilePage();
		}
		else
		{
			$alert = "Unknown event type: '$eventType'";
			echo $alert . '<br/>';
			echo '<script>alert("' . $alert . '");</script>';
			echo '<script>self.location="event.php?event=renderClasses&username=' . $_GET['username'] . '"</script>';
		}
	}
}
elseif($_SERVER['REQUEST_METHOD'] == 'POST')
{
	echo 'POST was used.<br/>';
	echo $_POST['studyGroupID'] . '<br/>';
	echo $_POST['event']  . '<br/>';
	echo 'Get was used.<br/>';
	if($_POST['event'] == null)
	{
		echo 'No event was received.<br/>';
		echo '<script>self.location="event.php?event=renderClasses"</script>';
	}
	else
	{
		$eventType = $_POST['event'];
		echo "Need to process the event: '$eventType' <br/>";	
		echo "Unknown event type: '$eventType' <br/>";
		echo '<script>self.location="event.php?event=renderClasses"</script>';
		
	}
	//deleteStudyGroup
}
else
{
	echo 'Neither get nor post were used.';
	echo '<script>self.location="event.php?event=renderClasses"</script>';
}

function beginPost($postTitle)
{
	echo '
	<div class="Post">
	<div class="PostHeader">
		'. $postTitle .'		
	</div>
	<div class="PostContent">
		';
}

function endPost()
{
	echo '				
	</div>
	</div>';
}
/* http://cs334b.educationvault.com/public/event.php?event=renderClasses&username=bob */
function renderClasses()
{	
	require ('../private/mysqli_connect.php');
	$postTitle = "Classes List";
	beginPost($postTitle);
	
	$query="SELECT * FROM course";
	$result= @mysqli_query($mysqli, $query);
	$numOfCourses = @mysqli_num_rows($result);
	//echo "<p>Number of classes found in database: {$numOfCourses}</p>";
		
	if($result && $numOfCourses > 0) 
	{
		while($row = mysqli_fetch_array($result))
		{
			$courseID = $row['c_id'];
			$courseName = $row['c_name'];
			$httpArray = array(	'username' => $_GET['username'],
								'event' => 'renderStudyGroups',
								'courseID' => $row['c_id'],
								'courseName' => $row['c_name']);
			$httpQuery = http_build_query($httpArray);
			//echo '<p>' .  $httpQuery . '</p>';

			$dynamicClassLink = '<p><a href="event.php?' . $httpQuery
						. '">' . $courseID . ": " . $courseName .'</a></p>';
			echo $dynamicClassLink;
			//echo "<p>{$courseID} </p>";			
		}
	}
	if($numOfCourses == 0)
	{
		echo "<p>No courses were found in the database. Some test inserts should have been included.
				Insert them into table 'course'.
				</p>";
	}
	endPost();
	mysqli_close($mysqli);
}
/* http://cs334b.educationvault.com/public/event.php?username=bob&event=renderStudyGroups&courseID=334&courseName=web+design */
/* Render the study groups based on the course description that was passed. */
function renderStudyGroups()
{
	/* ?event=renderStudyGroups&courseID=334&courseName=web+design */
	require ('../private/mysqli_connect.php');
	$courseID = $_GET['courseID'];
	$courseName = $_GET['courseName'];
	$postTitle = $courseID . ": " . $courseName . " Study Groups";
	beginPost($postTitle);
	renderCreateStudyGroupButton();
	
	$query="SELECT * FROM sGroup where c_id='{$courseID}'";
	$result= @mysqli_query($mysqli, $query);
	$numOfStudyGroups = @mysqli_num_rows($result);
	//echo "<p>Number of classes found in database: {$numOfStudyGroups}</p>";
		
	if($result && $numOfStudyGroups > 0) 
	{
		while($row = mysqli_fetch_array($result))
		{
			$httpArray = array(	'username' => $_GET['username'],
								'event' => 'renderStudyGroupPosts',
								'sg_id' => $row['sg_id'],
								'sg_name' => $row['sg_name'],
								'c_id' => $row['c_id']);
			$httpQuery = http_build_query($httpArray);
			//echo '<p>' . $httpQuery . '</p>';

			$dynamicClassLink = '<a href="event.php?' . $httpQuery
						. '">' . $row['sg_name'] . '</a>';
			echo $dynamicClassLink;
			renderDeleteButtonForStudyGroup($row['sg_id']);
			//echo '</p>';
			//echo "<p>{$courseID} </p>";			
		}
	}
	if($numOfStudyGroups == 0)
	{
		echo "<p>No study groups were found in the database. Some test inserts should have been included.
				Insert them into table 'sGroup'.
				</p>";
	}
	endPost();
	mysqli_close($mysqli);
}
/* ?studyGroupName=&event=createNewStudyGroup&username=bob&courseName=web+design&courseID=334 */

/* "insert into sGroup(sg_name, c_id, owning_u_id) values ('new study group', 334, 1)"; */
function createNewStudyGroup()
{
	echo "Creating new study group with name: '" . $_GET['studyGroupName'] . "'";
	
	require ('../private/mysqli_connect.php');
	$query = "select u_id from user_login where u_username ='{$_GET['username']}'";
	$result= @mysqli_query($mysqli, $query);	
	$userIDarray = mysqli_fetch_array($result);
	$userID = $userIDarray['u_id'];
	$courseID = $_GET['courseID'];
	$studyGroupName = $_GET['studyGroupName'];
	
	echo "the owning userID is: " . $userID['u_id'] . " study group name: " . $_GET['studyGroupName'];
	echo "  the course ID is: " . $courseID;
	$query="insert into sGroup(sg_name, c_id, owning_u_id) values
			('{$studyGroupName}', {$courseID}, {$userID})";
	//$query = "insert into sGroup(sg_name, c_id, owning_u_id) values ('bobs new study group', 334, 1)";
	$result= @mysqli_query($mysqli, $query);
	
	if($result) 
	{
		// successfully created new study group.
		echo '<script>
			alert("Successfully created new Study Group\n\nNote: no posts will appear.");
			</script>';		
	}
	else
	{
		// couldn't create new study group.
		echo '<script>
			alert("Problem creating new Study Group");
			</script>';
	}
	
	mysqli_close($mysqli);
	
	$httpArray = array(	'username' => $_GET['username'],
						'event' => 'renderClasses');
	$redirectUrl = buildDynamicGetQueryLink("event.php", $httpArray);
	echo '<script>self.location="' . $redirectUrl . '"</script>';
}

function buildDynamicGetQueryLink($phpPageName, $httpArray)
{	
	$httpQuery = http_build_query($httpArray);
	/*
	$httpArray = array(	'username' => $_GET['username'],
						'event' => 'createNewStudyGroup',
						'courseName' => $_GET['courseName'],
						'courseID' => $_GET['courseID']);
	*/	
	// $phpPageName = "page.php"
	$dynamicClassLink = $phpPageName .'?' . $httpQuery;
	return $dynamicClassLink;
}

/* ?username=bob&event=renderStudyGroups&courseID=334&courseName=web+design */
function renderCreateStudyGroupButton()
{

	$httpArray = array(	'username' => $_GET['username'],
						'event' => 'createNewStudyGroup',
						'courseName' => $_GET['courseName'],
						'courseID' => $_GET['courseID']);
	$httpQuery = http_build_query($httpArray);
	//echo '<p>' . $httpQuery . '</p>';

	$dynamicClassLink = '<p><a href="event.php?' . $httpQuery
				. '">' . $row['sg_name'] . '</a>';
	echo '<form name="create" method="get" action="render_event.php">
		<input type="submit" value="Create Study Group" />
		<input type="text" name="studyGroupName"/>
		<input type="hidden" name="event" value="createNewStudyGroup" />		
		<input type="hidden" name="username" value="' . $_GET['username']. '" />
		<input type="hidden" name="courseName" value="' . $_GET['courseName'] . '" />
		<input type="hidden" name="courseID" value="' . $_GET['courseID'] . '" />
	</form>
	';	
}

function renderDeleteButtonForStudyGroup($studyGroupID)
{
	// TODO: make this hidden after debugging
	echo '
	<form name="myform" method="get" action="render_event.php">
		<input type="submit" name="DeleteStudyGroup" value="Delete Study Group" />
		<input type="hidden" name="studyGroupID" value="'. $studyGroupID . '" />
		<input type="hidden" name="event" value="deleteStudyGroup" />		
		<input type="hidden" name="username" value="' . $_GET['username'] . '" />	
	</form>
	';
}

function deleteStudyGroup()
{
	require ('../private/mysqli_connect.php');
	$query="delete from sGroup where sg_id = " . $_GET['studyGroupID'];
	$result= @mysqli_query($mysqli, $query);
	$numOfPosts = @mysqli_num_rows($result);
	//echo "<p>Number of classes found in database: {$numOfPosts}</p>";
		
	if($result) 
	{
		echo '<script>alert("Deleted Study Group.")</script>;';
	}
	else
	{
		echo '<script>alert("Unable to delete Study Group.")</script>;';
	}
	mysqli_close($mysqli);
	redirectToClassesPage();
}

function redirectToClassesPage()
{
	$username = $_GET['username'];
	$event = 'renderClasses';
	$httpArray = array('username' => $username,
						'event' => $event
						);
	$dynamicLink = buildDynamicGetQueryLink("event.php", $httpArray);
	echo '<script>self.location="' .  $dynamicLink . '"</script>';
}

/* http://cs334b.educationvault.com/public/event.php?event=renderStudyGroupPosts&sg_id=36&sg_name=bobs+334+group&c_id=334 */
function renderStudyGroupPosts()
{
	// ?event=renderStudyGroupPosts&sg_id=36&sg_name=bobs+334+group&c_id=334
	require ('../private/mysqli_connect.php');
	$studyGroupName = $_GET['sg_name'];
	$courseID = $_GET['c_id'];
	//$postTitle = $courseID . " Study Group: " . $studyGroupName;
	$postTitle = $courseID . ": " . $studyGroupName;
	beginPost($postTitle);
	endPost();
	$studyGroupID = $_GET['sg_id'];
	$query="SELECT * FROM sGroupPost where sg_id={$studyGroupID} order by post_id asc";
	$result= @mysqli_query($mysqli, $query);
	$numOfPosts = @mysqli_num_rows($result);
	//echo "<p>Number of classes found in database: {$numOfPosts}</p>";
		
	if($result && $numOfPosts > 0) 
	{
		while($row = mysqli_fetch_array($result))
		{
			$userID = $row['u_id'];
			$getUsernameQuery="SELECT * FROM user_login where u_id={$userID}";
			$getUsernameResult= @mysqli_query($mysqli, $getUsernameQuery);
			$usernameRow = mysqli_fetch_array($getUsernameResult);
			$username = $usernameRow['u_username'];
			$postTitle = $username . " says ";			
			beginPost($postTitle);
			
			$postContent = $row['post_content'];
			echo $postContent;
			
			endPost();
		}
	}
	if($numOfPosts == 0)
	{
		echo "<p>No Posts were found in the database. Note: This may be because you added a study group.
				This functionality works, but posting wasn't required and I didn't have time.
				Adding some fake posts will work, though.
				</p>";
	}
	endPost();
	mysqli_close($mysqli);
	
}

function renderSearchPage()
{	
	require ('../private/mysqli_connect.php');
	$postTitle = "Search";
	beginPost($postTitle);
	
	echo '
	<form name="create" method="get" action="event.php">
		<input type="submit" value="Search Study Groups by Name" />
		<input type="text" name="searchString"/>
		<input type="hidden" name="event" value="displaySearchResults" />		
		<input type="hidden" name="username" value="' . $_GET['username']. '" />
	</form>
	';
	
	endPost();
	mysqli_close($mysqli);
}

function displaySearchResults()
{	
	require ('../private/mysqli_connect.php');
	$postTitle = "Search Results";
	beginPost($postTitle);
	$searchString = $_GET['searchString'];
	
	
	$query="SELECT * FROM sGroup WHERE sg_name LIKE  '%" . $searchString . "%' LIMIT 0 , 30";
	$result= @mysqli_query($mysqli, $query);
	$numOfThreads = @mysqli_num_rows($result);
	//echo "<p>Number of classes found in database: {$numOfThreads}</p>";
	
	echo '<p>Found ' . $numOfThreads .' results for "' . $searchString . '"</p>';
	if($result && $numOfThreads > 0) 
	{		
		while($row = mysqli_fetch_array($result))
		{
			$courseID = $row['c_id'];
			$courseName = $row['c_name'];
			$studyGroupName = $row['sg_name'];
			$studyGroupID = $row['sg_id'];
			$httpArray = array(	'username' => $_GET['username'],
								'event' => 'renderStudyGroupPosts',
								'c_id' => $courseID,
								'courseName' => $courseName,
								'sg_id' => $studyGroupID,
								'sg_name' => $studyGroupName
								);
			$dynamicClassLink = buildDynamicGetQueryLink("event.php", $httpArray);
			$displayText = $courseID . ": " . $studyGroupName;
			echo '<p><a href="' . $dynamicClassLink . '"</a>' . $displayText. '</p>' ;
			//echo "<p>{$courseID} </p>";			
		}
	}
	if($numOfThreads == 0)
	{
		echo "<p>No Study Group names contained '" . $searchString . "'.
				</p>";
	}
	endPost();
	mysqli_close($mysqli);
}
	
function renderProfilePage()
{
	require ('../private/mysqli_connect.php');
	$postTitle = "Profile";
	beginPost($postTitle);
	
	$httpArray = array(	'username' => $_GET['username'],
						'event' => 'createNewStudyGroup',
						'courseName' => $_GET['courseName'],
						'courseID' => $_GET['courseID']);
	$httpQuery = http_build_query($httpArray);
	//echo '<p>' . $httpQuery . '</p>';

	$dynamicClassLink = '<p><a href="event.php?' . $httpQuery
				. '">' . $row['sg_name'] . '</a>';
	/*
	echo '<form name="create" method="get" action="event.php">		
		<input type="text" name="password"/>
		<input type="hidden" name="event" value="createNewStudyGroup" />		
		<input type="hidden" name="username" value="' . $_GET['username']. '" />
		<input type="submit" value="Save" />
	</form>
	';
	*/
	
	endPost();
	mysqli_close($mysqli);
}

/*
	if($_SERVER['REQUEST_METHOD'] == 'GET')
	{
		$data = array('foo'=>'bar',
			  'baz'=>'boom',
			  'cow'=>'milk',
			  'php'=>'hypertext processor');
		$testGet = "test.php?" . http_build_query($data);
		//echo "<script>self.location=\"{$testGet}\";</script>";
		//exit;
		echo $_GET['a'] . "\n";
		echo $_GET['cat'] . '<br/>';
		$food = array('a' => 'roflcopter','cat' => 'more roflcopter');
		$query = http_build_query($food);
		echo $query;
		
		sleep(1);
		echo "<script>self.location=\"test.php?{$query}\";</script>";
		exit();
	}
*/

?>